import { defineStore } from "pinia";
import defaultSettings from "@/settings";
import type { SettingTypeEnum } from "@/enums/SettingTypeEnum";
import { useDynamicTitle } from "@/utils/dynamicTitle";
import type { Ref } from "vue";

export const useSettingsStore = defineStore("setting", () => {
  const storageSetting = JSON.parse(localStorage.getItem("layout-setting") || "{}");
  const prop: { [key: string]: Ref<any> } = {
    title: ref<string>(""),
    theme: ref<string>(storageSetting.theme || defaultSettings.theme),
    sideTheme: ref<string>(storageSetting.sideTheme || defaultSettings.sideTheme),
    showSettings: ref<boolean>(storageSetting.showSettings || defaultSettings.showSettings),
    tagsView: ref<boolean>(storageSetting.tagsView === undefined ? defaultSettings.tagsView : storageSetting.tagsView),
    sidebarLogo: ref<boolean>(
      storageSetting.sidebarLogo === undefined ? defaultSettings.sidebarLogo : storageSetting.sidebarLogo
    ),
    dynamicTitle: ref<boolean>(
      storageSetting.dynamicTitle === undefined ? defaultSettings.dynamicTitle : storageSetting.dynamicTitle
    ),
    animationEnable: ref<boolean>(
      storageSetting.animationEnable === undefined ? defaultSettings.animationEnable : storageSetting.animationEnable
    ),
    mode: ref<string>(storageSetting.mode || defaultSettings.mode),
    collapsedWidth: ref<number>(storageSetting.collapsedWidth || defaultSettings.collapsedWidth),
    copyright: ref<boolean>(storageSetting.copyright === undefined ? defaultSettings.copyright : storageSetting.copyright)
  };

  const {
    title,
    theme,
    sideTheme,
    showSettings,
    tagsView,
    sidebarLogo,
    dynamicTitle,
    animationEnable,
    mode,
    collapsedWidth,
    copyright
  } = prop;

  /**
   * 更改设置
   * @param param 参数
   */
  const changeSetting = (param: { key: SettingTypeEnum; value: any }) => {
    const { key, value } = param;
    if (key in prop) {
      prop[key].value = value;
    }
    const settings: any = useStorage<LayoutSetting>("layout-setting", defaultSettings);
    settings.value.mode = value;
  };

  // 设置站点名称
  const setTitle = (value: string) => {
    title.value = value;
    useDynamicTitle();
  };

  return {
    title,
    theme,
    sideTheme,
    showSettings,
    tagsView,
    sidebarLogo,
    dynamicTitle,
    animationEnable,
    mode,
    copyright,
    collapsedWidth,
    changeSetting,
    setTitle
  };
});

export default useSettingsStore;
